package com.max.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.max.constants.RoleType;
import com.max.dto.UserRegisterDTO;
import com.max.entity.UserInfo;
import com.max.exceptions.BusinessException;
import com.max.mapper.UserInfoMapper;
import com.max.service.IUserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements IUserInfoService {

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;


    @Override
    public int register(UserRegisterDTO dto) {
        //1.查询登录名称是否存在
        Long count = this.baseMapper.selectCount(new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getLoginName, dto.getLoginName()));
        if (count > 0) {
            throw new BusinessException("登录名称已存在");
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setRoleName(RoleType.ROLE_USER.getRoleName());
        userInfo.setRoleCode(RoleType.ROLE_USER.name());
        userInfo.setUsername(dto.getUsername());
        userInfo.setLoginName(dto.getLoginName());
        userInfo.setPwd(bCryptPasswordEncoder.encode(dto.getPwd()));
        return this.baseMapper.insert(userInfo);
    }
}
